package com.ymx.darling.dialect;

import com.ymx.darling.bean.sql.BoundSql;
import com.ymx.darling.bean.sql.SqlStatement;

import java.util.List;

public class SqlServerDialect implements Dialect {
    private String splitSql(String sql){
        return "select * from (select ROW_NUMBER() OVER(ORDER BY (select 0)) AS ROW_NUM, TMP.* from ( "
                + sql +
                " ) AS TMP) AS TMP2 WHERE ROW_NUM > ? and ROW_NUM <= ?";
    }

    @Override
    public String getDataBaseType() {
        return "sql server";
    }


    @Override
    public void paginate(BoundSql boundSql, int pageNum, int pageSize) {
        List<Object> paramList = boundSql.getRightParameters();
        int newPageNum = (pageNum - 1) * pageSize;
        int newPageSize = pageNum * pageSize;
        paramList.add(newPageNum);
        paramList.add(newPageSize);
        boundSql.setSql(this.splitSql(boundSql.getSql()));
    }

    @Override
    public void limit(SqlStatement statement, long limit, long offset) {
        List<Object> paramList = statement.getParamList();
        paramList.add(offset);
        paramList.add(offset + limit);
        statement.setSql(this.splitSql(statement.getSql()));
    }

    @Override
    public String currentDate() {
        return "CAST(GETDATE() AS DATE)";
    }

    @Override
    public String currentTime() {
        return "CONVERT(TIME, GETDATE())";
    }
}
